/** 
  维护基地考核设置
*/
<template>
  <div class="base-assess-set-container">
    <div class="close-dialog-btn" @click="cancel()">
      <i class="el-dialog__close el-icon el-icon-close"></i>
    </div>
    <el-tabs v-model="activeName" :before-leave="beforeLeave">
      <el-tab-pane :label="$t('baseAssessSetting.baseInfo')" name="baseInfo">
        <el-form :model="dialogForm" :disabled="this.dialogMode === 'details'" label-position="right" ref="dialogForm" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.examinationBatch') + ':'"
                prop="batch"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireExaminaBatch'), trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.batch"
                  type="month"
                  value-format="yyyy-MM"
                  :placeholder="$t('graduateBase.chooseMonth')">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.baseLevel') + ':'"
                prop="baseLevel"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireBaseLevel'), trigger: 'change'}]">
                <el-select v-model="dialogForm.baseLevel" @change="changeDialogBaseLevel" clearable style="width: 100%">
                  <el-option
                    v-for="item in options.baseLevel"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="$t('templateSetting.assessmentTemplate') + ':'"
                prop="templateId"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireTempId'), trigger: 'change'}]">
                <el-select v-model="dialogForm.templateId" clearable style="width: 100%">
                  <el-option
                    v-for="item in options.dailogTemplateId"
                    :key="item.templateId"
                    :label="item.templateName"
                    :value="item.templateId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('baseAssessSetting.involveBase') + ':'" prop="selectAllMark" :rules="[{ required: true, message: $t('baseAssessSetting.requireInvolveBase'), trigger: 'change'}]">
                <el-select v-model="dialogForm.selectAllMark" clearable @change="changeInvolveBase" multiple style="width: 100%">
                  <el-option
                    v-for="item in options.selectAllMark"
                    :key="item.id"
                    :label="item.baseName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.submitMaterialsStart') + ':'"
                prop="submitMaterialsStart"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireSubmitMaterialsStart'), trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.submitMaterialsStart"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('graduateBase.chooseDateAndTime')"
                  :picker-options="clbssjqPickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.submitMaterialsEnd') + ':'"
                prop="submitMaterialsEnd"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireSubmitMaterialsEnd'), trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.submitMaterialsEnd"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('graduateBase.chooseDateAndTime')"
                  :picker-options="clbssjzPickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.onSiteAssessTimeStart') + ':'"
                prop="onSiteExamineStart"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireOnSiteAssessTimeStart'), trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.onSiteExamineStart"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('graduateBase.chooseDateAndTime')"
                  :picker-options="xckhsjqPickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.onSiteAssessTimeEnd') + ':'"
                prop="onSiteExamineEnd"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireOnSiteAssessTimeEnd'), trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.onSiteExamineEnd"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('graduateBase.chooseDateAndTime')"
                  :picker-options="xckhsjzPickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.ratingTimeStart') + ':'"
                prop="scoreStart"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireRatingTimeStart'), trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.scoreStart"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('graduateBase.chooseDateAndTime')"
                  :picker-options="pfsjqPickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="$t('baseAssessSetting.ratingTimeEnd') + ':'"
                prop="scoreEnd"
                :rules="[{ required: true, message: $t('baseAssessSetting.requireRatingTimeEnd'), trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.scoreEnd"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('graduateBase.chooseDateAndTime')"
                  :picker-options="pfsjzPickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
              :label="$t('baseAssessSetting.examinationDescrip') + ':'"
              prop="examineExplain"
              :rules="[{ validator: this.checkSpecial, trigger: 'blur'}]">
              <el-input type="textarea" :maxlength="1000" :rows="7" v-model="dialogForm.examineExplain" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane :label="$t('baseAssessSetting.expertsSet')" name="expertsSet">
        <div v-if="dialogMode !== 'details' && !(activeName === 'expertsSet' && dialogForm.publishStatus === 1)" style="float: right;margin-bottom: 15px;">
          <el-button v-if="permitToAddExperts" type="primary" @click="addExperts">{{ $t('common.btn.add') }}</el-button>
          <el-button v-if="permitToDelExperts" type="danger" @click="deleteExperts">{{$t('common.btn.delete')}}</el-button>
        </div>
        <edu-table :selection="dialogMode === 'details' ? false : true" :pagination="false" :order='false' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleDialogSelectionChange">
          <edu-table-column :label="$t('baseAssessSetting.name')" prop="name"></edu-table-column>
          <edu-table-column :label="$t('baseAssessSetting.department')" prop="department"></edu-table-column>
          <edu-table-column :label="$t('baseAssessSetting.proTitle')" prop="proTitle"></edu-table-column>
          <edu-table-column :label="$t('baseAssessSetting.contactPhone')" prop="contactPhone"></edu-table-column>
        </edu-table>
      </el-tab-pane>
    </el-tabs>
    <div class="dialog-footer">
      <template v-if="dialogMode === 'add' || dialogMode === 'edit'">
        <el-button @click="cancel()">{{ $t('common.btn.cancel') }}</el-button>
        <el-button v-if="!(activeName === 'expertsSet' && dialogForm.publishStatus === 1) && dialogMode === 'add'" @click="resetDialog('dialogForm')">{{ $t('common.btn.reset') }}</el-button>
        <el-button v-if="!(activeName === 'expertsSet' && dialogForm.publishStatus === 1)"  type="primary" @click="saveDialog()">{{$t('common.btn.save')}}</el-button>
        <el-button v-if="!(activeName === 'expertsSet' && dialogForm.publishStatus === 1)"  type="primary" @click="publishDialog('dialogForm')">{{$t('common.btn.publish')}}</el-button>
      </template>
      <template v-else-if="dialogMode === 'details'">
        <el-button @click="closeDialog('dialogForm')">{{$t('common.btn.close')}}</el-button>
      </template>
    </div>
    <el-dialog
      width="25%"
      ref="innerDialog"
      :title="$t('graduateBase.prompt')"
      :visible.sync="innerVisible"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :top="'28vh'">
      <div style="text-align: left;margin-bottom: 25px;">{{$t('graduateBase.cancelTip')}}</div>
      <div style="text-align: right;">
        <el-button type="primary" @click="confirmInner('innerDialog')">{{$t('common.btn.confirm')}}</el-button>
        <el-button @click="cancelInner('innerDialog')">{{$t('common.btn.cancel')}}</el-button>
        <el-button type="primary" @click="confirmAndClose('dialogForm')">{{$t('graduateBase.saveAndClose')}}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :before-close="closeExpertsInfo"
      width="70%"
      ref="expertsDialog"
      :title="$t('baseAssessSetting.expertsChoose')"
      :visible.sync="expertsVisible"
      append-to-body
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :top="'15vh'">
      <experts-info @filter-experts-info="getExperts" @close-experts-info="closeExpertsInfo"></experts-info>
    </el-dialog>
  </div>
</template>
<script>
import UTILS from "common/src/utils/utils";
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
import expertsInfo from './expertsInfo.vue';
export default {
  components: {
    'experts-info': expertsInfo
  },
  data () {
    return {
      activeName: 'baseInfo',
      permitToAddExperts: true,
      permitToDelExperts: true,
      baseAssessSetId: '',
      dialogForm: {
        "batch": "",
        "baseLevel": "",
        "templateId": "",
        "submitMaterialsStart": "",
        "submitMaterialsEnd": "",
        "onSiteExamineStart": "",
        "onSiteExamineEnd": "",
        "scoreStart": "",
        "scoreEnd": "",
        "examineExplain": "",
        "selectAllMark": [],
        "baseList": []
      },
      options: {
        // 基地级别
        baseLevel: [
          {
            label: '校级',
            value: '1'
          },
          {
            label: '院级',
            value: '2'
          }
        ],
        dailogTemplateId: [],
        selectAllMark: [] // 涉及基地
      },
      dataList: [],
      multipleSelection: [],
      expertsVisible: false,
      innerVisible: false,
      baseAssessData: {},
      originDialogForm: {}
    };
  },
  props: {
    dialogMode: {
      type: String,
      default: 'add'
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    mainBaseAssessInfo: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    clbssjqPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.dialogForm.submitMaterialsEnd) {
            // 材料报送开始时间必须小于材料报送截止时间
            if (value.getTime() > new Date(_this.dialogForm.submitMaterialsEnd.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    },
    clbssjzPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.dialogForm.submitMaterialsStart) {
            // 材料报送截止时间必须大于材料报送开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.dialogForm.submitMaterialsStart.split(' ')[0]).getTime()) {
              return true
            }
          }
          if (_this.dialogForm.onSiteExamineStart) {
            // 材料报送截止时间必须小于现场考核开始时间
            if (value.getTime() > new Date(_this.dialogForm.onSiteExamineStart.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false
        }
      }
    },
    xckhsjqPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
           if (_this.dialogForm.submitMaterialsEnd) {
            // 现场考核开始时间必须大于材料报送截止时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.dialogForm.submitMaterialsEnd.split(' ')[0]).getTime()) {
              return true;
            }
          }
          if (_this.dialogForm.onSiteExamineEnd) {
            // 现场考核开始时间必须小于现场考核截止时间
            if (value.getTime() > new Date(_this.dialogForm.onSiteExamineEnd.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    },
    xckhsjzPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.dialogForm.onSiteExamineStart) {
            // 现场考核截止时间必须大于现场考核开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.dialogForm.onSiteExamineStart.split(' ')[0]).getTime()) {
              return true
            }
          }
          if (_this.dialogForm.scoreStart) {
            // 现场考核截止时间必须小于评分开始时间
            if (value.getTime() > new Date(_this.dialogForm.scoreStart.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false
        }
      }
    },
    pfsjqPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.dialogForm.onSiteExamineEnd) {
            // 评分开始时间必须大于现场考核截止时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.dialogForm.onSiteExamineEnd.split(' ')[0]).getTime()) {
              return true;
            }
          }
          if (_this.dialogForm.scoreEnd) {
            // 评分开始时间必须小于评分截止时间
            if (value.getTime() > new Date(_this.dialogForm.scoreEnd.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    },
    pfsjzPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.dialogForm.scoreStart) {
            // 评分截止时间必须大于评分开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.dialogForm.scoreStart.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    }
  },
  mounted() {
    if (this.dialogMode === 'add') {
      this.$refs['dialogForm'].resetFields()
    }
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    changeInvolveBase(val) {
      let value = JSON.parse(JSON.stringify(val))
      let currentValue = value[value.length - 1]
      if (currentValue === '0') {
        this.dialogForm.selectAllMark = ['0']
      } else if (currentValue !== '0' && val.indexOf('0') > -1 && val.length > 1) {
        value.splice(val.indexOf('0'), 1)
        this.dialogForm.selectAllMark = value
      }
      this.$forceUpdate()
    },
    beforeLeave(activeName, oldActiveName) {
      if (this.dialogMode !== 'details') {
        if (activeName === 'expertsSet') {
          if (!this.baseAssessSetId) {
            this.$message.info(this.$t('baseAssessSetting.shouldSetBaseAssess'))
            return false
          }
        }
      }
    },
    closeDialog() {
      this.$refs['dialogForm'].resetFields()
      this.$emit('close-base-assess-set')
    },
    // 根据基地级别改变涉及基地数组
    async changeSelectAllMarkArray(val) {
      this.options.selectAllMark = [
        {
          id: '0',
          baseName: '全部'
        }
      ]
      const response = await graduateStudentApi.getInvolveBases(val)
      if (response.data.length > 0) {
        response.data.map((item) => {
          this.options.selectAllMark.push(item)
        })
      } else {
        this.options.selectAllMark = []
      }
    },
    // 根据基地级别改变考核模板
    async changeTemplateIdArray(val) {
      const response = await graduateStudentApi.getHasDetailTemp({
        "itemCategory": "1",
        "baseTemplate": {
          "baseLevel": val
        }
      })
      if (response.code === 200) {
        this.options.dailogTemplateId = response.data
      }
    },
    // 修改弹框中的基地级别
    changeDialogBaseLevel(val) {
      this.dialogForm.templateId = ''
      this.dialogForm.selectAllMark = []
      this.changeTemplateIdArray(val)
      this.changeSelectAllMarkArray(val)
    },
    // 新增专家
    addExperts() {
      this.expertsVisible = true
    },
    // 关闭专家弹出框
    closeExpertsInfo() {
      this.expertsVisible = false
    },
    // 前台删除专家，不调用接口
    softDeleteExperts(key) {
      let _this = this;
      for (let i = _this.dataList.length - 1; i >= 0; i--) {
        _this.dataList[i]['uniqueId'] = _this.dataList[i][key]
        _this.multipleSelection.map((element) => {
          if (_this.dataList[i]) {
            if ((_this.dataList[i][key] && _this.dataList[i][key] === element[key])) {
              _this.dataList.splice(i, 1)
            }
          }
        })
      }
    },
    // 删除专家
    deleteExperts() {
      let _this = this
      if (this.multipleSelection.length > 0) {
        if (this.dialogMode === 'add') {
          this.$delConfirm().then(_ => {
            this.softDeleteExperts('id')
          })
        } else {
          this.$delConfirm().then(async _ => {
            let hasSettingId = false
            let notHasSettingId = false
            let hasSettingIdArray = []
            let notHasSettingIdArray = []
            let currentDelIds = []
            _this.multipleSelection.map((element) => {
              if (element.settingId) {
                hasSettingId = true
                element['uniqueId'] = element.specialistId
                hasSettingIdArray.push(element)
                currentDelIds.push(element.id)
              } else {
                notHasSettingId = true
                element['uniqueId'] = element.id
                notHasSettingIdArray.push(element)
              }
            })
            let targetArray = hasSettingIdArray.concat(notHasSettingIdArray)
            if (hasSettingId) {
              const deleteResult = await graduateStudentApi.batchDelReviewExperts({
                "id": this.baseAssessSetId,
                "specialistIdList": currentDelIds
              })
              if (deleteResult.code === 200) {
                for (let i = _this.dataList.length - 1; i >= 0; i--) {
                  targetArray.map((element) => {
                    if (_this.dataList[i]) {
                      if ((_this.dataList[i].uniqueId && _this.dataList[i].uniqueId === element.uniqueId)) {
                        _this.dataList.splice(i, 1)
                      }
                    }
                  })
                }
                this.$message.success(this.$t('common.tips.deleteSuccess'))
              } else {
                return
              }
            } else if (notHasSettingId && !hasSettingId){
              for (let i = _this.dataList.length - 1; i >= 0; i--) {
                targetArray.map((element) => {
                  if (_this.dataList[i]) {
                    if ((_this.dataList[i].uniqueId && _this.dataList[i].uniqueId === element.uniqueId)) {
                      _this.dataList.splice(i, 1)
                    }
                  }
                })
              }
              this.$message.success(this.$t('common.tips.deleteSuccess'))
            }
          })
        }
      } else {
        this.$message.info(this.$t('baseAssessSetting.shouldChooseExpert'))
      }
    },
    handleDialogSelectionChange(val) {
      this.multipleSelection = val
    },
    // 重置基地考核设置--表单
    resetDialog() {
      if (this.activeName === 'baseInfo') {
        this.$refs['dialogForm'].resetFields()
        this.options.dailogTemplateId = []
        this.options.selectAllMark = [
          {
            baseName: '全部',
            id: '0'
          }
        ]
      } else {
        this.dataList = []
      }
      
    },
    // 处理保存接口的传参
    dealWithBaseInfoParams() {
      let copyDialogForm = {...this.dialogForm}
      let params = {
        "batch": copyDialogForm.batch,
        "baseLevel": copyDialogForm.baseLevel,
        "templateId": copyDialogForm.templateId,
        "submitMaterialsStart": copyDialogForm.submitMaterialsStart,
        "submitMaterialsEnd": copyDialogForm.submitMaterialsEnd,
        "onSiteExamineStart": copyDialogForm.onSiteExamineStart,
        "onSiteExamineEnd": copyDialogForm.onSiteExamineEnd,
        "scoreStart": copyDialogForm.scoreStart,
        "scoreEnd": copyDialogForm.scoreEnd,
        "examineExplain": copyDialogForm.examineExplain,
        "selectAllMark": copyDialogForm.selectAllMark.indexOf('0') > -1 ? 1 : 0
      }
      if (this.baseAssessSetId) {
        params['id'] = this.baseAssessSetId
      }
      let baseList = []
      if (copyDialogForm.selectAllMark.indexOf('0') === -1) {
        if (copyDialogForm.selectAllMark.length > 0) {
          copyDialogForm.selectAllMark.map((item) => {
            baseList.push({
              'baseId': item,
              'baseName': UTILS.translateLabel(this.options.selectAllMark, item, 'id', 'baseName')
            })
          })
        }
        params['baseList'] = baseList
      }
      return params
    },
    // 保存基地考核设置-基本信息
    saveBaseInfo(val) {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          if (this.dialogForm.submitMaterialsStart > this.dialogForm.submitMaterialsEnd) {
            this.$eduAlert(this.$t('baseAssessSetting.materialTimeTip'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          if (this.dialogForm.submitMaterialsEnd > this.dialogForm.onSiteExamineStart) {
            this.$eduAlert(this.$t('baseAssessSetting.materialAndAssessTime'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          if (this.dialogForm.onSiteExamineStart > this.dialogForm.onSiteExamineEnd) {
            this.$eduAlert(this.$t('baseAssessSetting.assessTimeTip'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          if (this.dialogForm.onSiteExamineEnd > this.dialogForm.scoreStart) {
            this.$eduAlert(this.$t('baseAssessSetting.assessAndScoreTime'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          if (this.dialogForm.scoreStart > this.dialogForm.scoreEnd) {
            this.$eduAlert(this.$t('baseAssessSetting.scoreTimeTip'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          let params = this.dealWithBaseInfoParams()
          if (this.baseAssessSetId) {
            if (this.dataList.length > 0) {
              let currentExperts = [];
              this.dataList.map((item) => {
                currentExperts.push({
                  "specialistId": item.specialistId ? item.specialistId : item.id
                })
              })
              params['besettingSpecialistList'] = currentExperts
            }
            graduateStudentApi.modifyBaseAssessSet(params).then(res => {
              if (res.code === 200) {
                this.$message.success(this.$t('graduateBase.savedSuccessfully'))
                this.$emit('close-base-assess-set')
                this.$emit('refresh-base-assess-set')
              }
            })
          } else {
            graduateStudentApi.saveBaseAssessSet(params).then(res => {
              if (res.code === 200) {
                this.baseAssessSetId = res.data.id
                this.$message.success(this.$t('graduateBase.savedSuccessfully'))
                if (val) {
                 this.$emit('close-base-assess-set') 
                }
                this.$emit('refresh-base-assess-set')
                this.saveExperts()
              }
            })
          }
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error")
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus()
            }
          }, 1)
        }
      })
    },
    // 新增基地考核设置-专家
    saveExperts() {
      if (this.dialogMode === 'edit' && this.dataList.length === 0) {
        this.$message.info(this.$t('baseAssessSetting.shouldChooseExperts'))
        return
      }
      if (this.dataList.length > 0) {
        let currentExperts = []
        this.dataList.map((item) => {
          currentExperts.push({
            "specialistId": item.id
          })
        })
        let params = {
          "id": this.baseAssessSetId,
          "besettingSpecialistList": currentExperts
        }
        graduateStudentApi.addReviewExperts(params).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t('graduateBase.savedSuccessfully'))
            this.$emit('close-base-assess-set')
          }
        })
      }
    },
    // 保存基地考核设置--表单
    saveDialog(val) {
      this.saveBaseInfo(val)
    },
    // 保存并发布基地考核设置
    publishDialog() {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          if (this.dataList.length === 0) {
            this.$message.info(this.$t('baseAssessSetting.shouldChooseExperts'))
            return
          }
          if (this.dialogForm.submitMaterialsStart > this.dialogForm.submitMaterialsEnd) {
            this.$eduAlert(this.$t('baseAssessSetting.materialTimeTip'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          if (this.dialogForm.onSiteExamineStart > this.dialogForm.onSiteExamineEnd) {
            this.$eduAlert(this.$t('baseAssessSetting.assessTimeTip'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          if (this.dialogForm.scoreStart > this.dialogForm.scoreEnd) {
            this.$eduAlert(this.$t('baseAssessSetting.scoreTimeTip'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          let params = this.dealWithBaseInfoParams()
          params['publishStatus'] = '1'
          let currentExperts = []
            if (this.dataList.length > 0) {
              this.dataList.map((item) => {
                currentExperts.push({
                  "specialistId": item.specialistId ? item.specialistId : item.id
                })
              })
            }
          params['besettingSpecialistList'] = currentExperts
          graduateStudentApi.saveAndPublishBaseAssessSet(params).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('graduateBase.saveAndPublish'))
              this.$emit('close-base-assess-set')
              this.$emit('refresh-base-assess-set')
            }
          })
        } else {
          this.activeName = 'baseInfo'
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error")
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus()
            }
          }, 1)
        }
      })
    },
    // 获取到选择的专家
    getExperts(val) {
      let chooseArray = val
      if (chooseArray.length > 0) {
        chooseArray.forEach((item) => {
          item['uniqueId'] = item.id
        })
      }
      let sourceArray = JSON.parse(JSON.stringify(this.dataList))
      if (sourceArray.length > 0) {
        sourceArray.forEach((element, index) => {
          if (element.settingId) {
            element['uniqueId'] = element.specialistId
          } else {
            element['uniqueId'] = element.id
          }
        })
      }
      let targetArray = JSON.parse(JSON.stringify(sourceArray))
      targetArray.map((item, index) => {
        chooseArray.map((element, valIndex) => {
          if (item.uniqueId === element.uniqueId) {
            chooseArray.splice(valIndex, 1)
          }
        })
      })
      this.dataList = sourceArray.concat(chooseArray)
    },
    cancel() {
      let allIsEmpty = true;
      if (this.dialogMode === 'add') {
        for (let key in this.dialogForm) {
          if (Array.isArray(this.dialogForm[key]) && this.dialogForm[key].length > 0) {
            allIsEmpty = false
          } else if (!Array.isArray(this.dialogForm[key]) && this.dialogForm[key]) {
            allIsEmpty = false
          }
        }
        if (this.dataList.length > 0) {
          allIsEmpty = false
        }
      }
      if ((this.dialogMode === 'add' && allIsEmpty) || this.dialogMode === 'details') {
        this.innerVisible = false
        this.$emit('close-base-assess-set')
      } else {
        this.innerVisible = true
      }
    },
    // 内层确认框-确认
    confirmInner() {
      this.innerVisible = false
      this.$emit('close-base-assess-set')
    },
    // 内层确认框-取消
    cancelInner() {
      this.innerVisible = false
    },
    // 内层确认框-保存并取消
    confirmAndClose(formName) {
      this.innerVisible = false
      this.saveDialog(1)
    }
  },
  watch: {
    dialogVisible: {
      handler(newVal) {
        if (!newVal) {
          if (this.$refs['dialogForm']) {
            this.$refs['dialogForm'].resetFields()
            Object.keys(this.dialogForm).forEach(key => this.dialogForm[key] = '')
            this.dialogForm.selectAllMark = []
            this.dialogForm.baseList = []
            this.options.dailogTemplateId = []
            this.options.selectAllMark = []
          }
          this.activeName = 'baseInfo'
          this.baseAssessSetId = ''
          this.dataList = []
        }
      },
      deep: true,
      immediate: true
    },
    mainBaseAssessInfo: {
      handler(newVal) {
        if (newVal) {
          if (this.dialogMode !== 'add') {
            this.dialogForm = JSON.parse(JSON.stringify(newVal))
            if (newVal.selectAllMark === 1) {
              this.dialogForm.selectAllMark = ['0']
            } else if (newVal.selectAllMark === 0 && Array.isArray(newVal.baseList) && newVal.baseList.length > 0) {
              this.dialogForm.selectAllMark = newVal.baseList.map(item => {
                return item.baseId
              })
            }
            this.originDialogForm = JSON.parse(JSON.stringify(this.dialogForm))
            if (newVal.baseLevel) {
              this.changeSelectAllMarkArray(newVal.baseLevel)
              this.changeTemplateIdArray(newVal.baseLevel)
            }
            this.dataList = this.dialogForm.besettingSpecialistList
            this.baseAssessSetId = newVal.id
          }
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
  .base-assess-set-container ::v-deep {
    .el-tabs__content {
      padding: 0 20px;
    }
    .el-tabs__nav-wrap {
      padding: 0 20px;
    }
  }
  .close-dialog-btn {
    position: absolute;
    right: 10px;
    top: 20px;
    color: #909399;
    cursor: pointer;
    width: 20px;
    height: 20px;
    z-index: 99999;
  }
  .close-dialog-btn:hover {
    color: #409EFF;
  }
  .dialog-footer {
    margin-top: 15px;
    padding: 20px 20px 5px 0;
    text-align: right;
    border-top: 1px solid #c0c4cc;
  }
</style>